package top.shiyiri.filter;

import com.alibaba.druid.util.JdbcUtils;
import top.shiyiri.utils.JDBCUtils;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author Aunean
 * @date 2022/2/12 17:02
 */
public class TransactionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        try {
            filterChain.doFilter(servletRequest, servletResponse);
            JDBCUtils.commitAndClose();
        } catch (Exception e) {
            JDBCUtils.rollbackAndClose();
            e.printStackTrace();
            throw new RuntimeException(e); //把异常抛给Tomcat服务器统一显示错误页面
        }
    }

    @Override
    public void destroy() {

    }
}
